/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package dp1.titandevelop.titano.view.sec;

import dp1.titandevelop.titano.persistent.Empleado;
import dp1.titandevelop.titano.persistent.PermisoXPerfil;
import dp1.titandevelop.titano.persistent.Usuario;
import dp1.titandevelop.titano.service.EmpleadoService;
import dp1.titandevelop.titano.service.UsuarioService;
import dp1.titandevelop.titano.service.ValidacionService;
import dp1.titandevelop.titano.view.LoginT;
import java.awt.Dimension;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JOptionPane;
import javax.swing.table.AbstractTableModel;

/**
 *
 * @author chrestean
 */
public class ModulosT_SEG_AUsu extends javax.swing.JInternalFrame {

    public List<Usuario> listaUsuarios;
    public List<Empleado> listaEmpleados;
    public ModulosT_SEG_AUsuEdit ventanaEdita;

    public void RefreshTable() {

        AbstractTableModel aux = (AbstractTableModel) tablaUsuarios.getModel();
        aux.fireTableDataChanged();
    }

    public void habilitaBotones() {
        this.btnEditar.setEnabled(true);
        this.btnEliminar.setEnabled(true);
    }

    private void inhabilitaBotones() {
        this.btnEditar.setEnabled(false);
        this.btnEliminar.setEnabled(false);
    }
    private AbstractTableModel ModeloTabla = new AbstractTableModel() {
        //Atributos de los datos de la tabla
        private String[] titles = {"Usuario", "Nombre", "Ap. Paterno", "Ap. Materno"};

        public int getRowCount() {
            return listaUsuarios.size();//tipos.size(); // cuantos registros (filas)
        }

        public int getColumnCount() {
            return 4; // cuantas columnas
        }

        @Override
        public String getColumnName(int col) {
            return titles[col];
        }

        public Object getValueAt(int rowIndex, int columnIndex) {
            Object resultado = null;
            Usuario user = listaUsuarios.get(rowIndex);
            Empleado emp = listaEmpleados.get(rowIndex);
            switch (columnIndex) {
                case 0:
                    resultado = user.getUsuario();
                    break;
                case 1:
                    resultado = emp.getNombres();
                    break;
                case 2:
                    resultado = emp.getApellidop();
                    break;
                case 3:
                    resultado = emp.getApellidom();
                    break;
            }
            return resultado;
        }
    };
    public static ModulosT_SEG_AUsuNuevo admUserNew = null;

    /**
     * Creates new form TitanoInteralSegADMUser
     */
    public ModulosT_SEG_AUsu() {
        initComponents();
        ValidacionService validacionService = new ValidacionService();
        this.listaUsuarios = new ArrayList<Usuario>();
        this.tablaUsuarios.setModel(ModeloTabla);
        validacionService.SLetras(this.txtNombre);
        validacionService.Longitud(this.txtNombre, 30);
        validacionService.SLetras(this.txtMaterno);
        validacionService.Longitud(this.txtMaterno, 15);
        validacionService.SLetras(this.txtAPaterno);
        validacionService.Longitud(this.txtAPaterno, 15);
        validacionService.SLetras(this.txtUsuario);
        validacionService.Longitud(this.txtUsuario, 10);
        inhabilitaBotones();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        botonBuscar = new javax.swing.JButton();
        jPanel1 = new javax.swing.JPanel();
        lblNombre = new javax.swing.JLabel();
        lblAPaterno = new javax.swing.JLabel();
        lblAMaterno = new javax.swing.JLabel();
        lblUsuario = new javax.swing.JLabel();
        txtNombre = new javax.swing.JTextField();
        txtAPaterno = new javax.swing.JTextField();
        txtMaterno = new javax.swing.JTextField();
        txtUsuario = new javax.swing.JTextField();
        botonLimpiar = new javax.swing.JButton();
        botonNuevo = new javax.swing.JButton();
        jPanel2 = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        tablaUsuarios = new javax.swing.JTable();
        botonSalir = new javax.swing.JButton();
        btnEditar = new javax.swing.JButton();
        btnEliminar = new javax.swing.JButton();

        setResizable(true);
        setTitle("Administrar Usuario");
        setToolTipText("");
        setMaximumSize(new java.awt.Dimension(600, 450));
        setMinimumSize(new java.awt.Dimension(600, 450));
        setName(""); // NOI18N
        setPreferredSize(new java.awt.Dimension(600, 450));

        botonBuscar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/img/buscar.png"))); // NOI18N
        botonBuscar.setToolTipText("Buscar");
        botonBuscar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                botonBuscarActionPerformed(evt);
            }
        });

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("Filtros de Búsqueda"));
        jPanel1.setFont(new java.awt.Font("Tekton Pro", 0, 11)); // NOI18N

        lblNombre.setText("Nombre");

        lblAPaterno.setText("Ap. Paterno");

        lblAMaterno.setText("Ap. Materno");

        lblUsuario.setText("Usuario");

        txtNombre.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                txtNombreKeyPressed(evt);
            }
            public void keyTyped(java.awt.event.KeyEvent evt) {
                txtNombreKeyTyped(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(lblNombre)
                        .addGap(42, 42, 42)
                        .addComponent(txtNombre, javax.swing.GroupLayout.PREFERRED_SIZE, 102, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(lblAPaterno)
                        .addGap(21, 21, 21)
                        .addComponent(txtAPaterno, javax.swing.GroupLayout.PREFERRED_SIZE, 102, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addGap(78, 78, 78)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(lblUsuario)
                    .addComponent(lblAMaterno))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(txtMaterno, javax.swing.GroupLayout.DEFAULT_SIZE, 105, Short.MAX_VALUE)
                    .addComponent(txtUsuario))
                .addGap(75, 75, 75))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(8, 8, 8)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lblNombre)
                    .addComponent(lblUsuario)
                    .addComponent(txtNombre, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(txtUsuario, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(15, 15, 15)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(lblAPaterno)
                    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(txtAPaterno, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(txtMaterno, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(lblAMaterno)))
                .addGap(8, 8, 8))
        );

        botonLimpiar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/img/limpiar.png"))); // NOI18N
        botonLimpiar.setToolTipText("Limpiar");
        botonLimpiar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                botonLimpiarActionPerformed(evt);
            }
        });

        botonNuevo.setIcon(new javax.swing.ImageIcon(getClass().getResource("/img/nuevo.png"))); // NOI18N
        botonNuevo.setToolTipText("Nuevo");
        botonNuevo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                botonNuevoActionPerformed(evt);
            }
        });

        jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder("Resultado de Búsqueda"));
        jPanel2.setFont(new java.awt.Font("Tekton Pro", 0, 11)); // NOI18N

        tablaUsuarios.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Usuario", "Nombre", "Ap. Paterno", "Ap. Materno"
            }
        ));
        tablaUsuarios.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                tablaUsuariosMouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(tablaUsuarios);

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 513, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(8, 8, 8))
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 116, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(8, 8, 8))
        );

        botonSalir.setIcon(new javax.swing.ImageIcon(getClass().getResource("/img/retroceder.png"))); // NOI18N
        botonSalir.setToolTipText("Salir");
        botonSalir.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                botonSalirActionPerformed(evt);
            }
        });

        btnEditar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/img/editar.png"))); // NOI18N
        btnEditar.setToolTipText("Editar");
        btnEditar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnEditarActionPerformed(evt);
            }
        });

        btnEliminar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/img/eliminar.png"))); // NOI18N
        btnEliminar.setToolTipText("Eliminar");
        btnEliminar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnEliminarActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(8, 8, 8)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(0, 426, Short.MAX_VALUE)
                        .addComponent(btnEditar)
                        .addGap(1, 1, 1)
                        .addComponent(btnEliminar))
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                        .addGroup(layout.createSequentialGroup()
                            .addComponent(botonBuscar)
                            .addGap(0, 0, 0)
                            .addComponent(botonNuevo)
                            .addGap(0, 0, 0)
                            .addComponent(botonLimpiar)
                            .addGap(0, 0, 0)
                            .addComponent(botonSalir))
                        .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
                .addContainerGap(19, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(8, 8, 8)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(botonBuscar)
                    .addComponent(botonNuevo)
                    .addComponent(botonLimpiar)
                    .addComponent(botonSalir))
                .addGap(8, 8, 8)
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(8, 8, 8)
                .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(8, 8, 8)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(btnEditar)
                    .addComponent(btnEliminar))
                .addContainerGap(54, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void botonNuevoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_botonNuevoActionPerformed

        //ID 09

        Integer i = 0;
        for (; i < LoginT.permisosxperfil.size(); i++) {
            if (9 == (Integer) LoginT.idspermisosxperfil.get(i)) {

                admUserNew = new ModulosT_SEG_AUsuNuevo();

                this.getParent().add(admUserNew);
                Dimension desktopSize = this.getParent().getSize();
                Dimension jInternalFrameSize = admUserNew.getSize();
                admUserNew.setLocation((desktopSize.width - jInternalFrameSize.width) / 2,
                        (desktopSize.height - jInternalFrameSize.height) / 4);
                admUserNew.show();
                this.dispose();


                break;
            }

        }
        if (i >= LoginT.permisosxperfil.size()) {
            JOptionPane.showMessageDialog(this, "No puedes proceder, al parecer careces de permisos.",
                    "No posee permisos",
                    JOptionPane.WARNING_MESSAGE);
        }




    }//GEN-LAST:event_botonNuevoActionPerformed

    private void botonBuscarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_botonBuscarActionPerformed
        UsuarioService usuarioService = new UsuarioService();
        EmpleadoService empleadoService = new EmpleadoService();
        this.listaUsuarios = usuarioService.buscarUsuariobyEmpleado(this.txtUsuario.getText(), this.txtNombre.getText(), this.txtAPaterno.getText(), this.txtMaterno.getText());
        if (listaUsuarios.isEmpty()) {
            this.RefreshTable();
        } else {
            this.listaEmpleados = empleadoService.buscarEmpleadoParametrosUsuario(this.txtUsuario.getText(), this.txtNombre.getText(), this.txtAPaterno.getText(), this.txtMaterno.getText());
            this.RefreshTable();
        }

    }//GEN-LAST:event_botonBuscarActionPerformed

    private void botonSalirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_botonSalirActionPerformed
        this.dispose();
    }//GEN-LAST:event_botonSalirActionPerformed

    private void btnEditarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnEditarActionPerformed
        Usuario usuarioSeleccionado = listaUsuarios.get(this.tablaUsuarios.getSelectedRow());
        Empleado empleadoSeleccionado = listaEmpleados.get(this.tablaUsuarios.getSelectedRow());

        ventanaEdita = new ModulosT_SEG_AUsuEdit(usuarioSeleccionado, empleadoSeleccionado);
        this.getParent().add(ventanaEdita);
        Dimension desktopSize = this.getParent().getSize();
        Dimension jInternalFrameSize = ventanaEdita.getSize();
        ventanaEdita.setLocation((desktopSize.width - jInternalFrameSize.width) / 2, (desktopSize.height - jInternalFrameSize.height) / 4);
        ventanaEdita.show();
        this.dispose();

    }//GEN-LAST:event_btnEditarActionPerformed

    private void btnEliminarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnEliminarActionPerformed
     
        //ID 10 Eliminar/Guardar usuario
        Integer i = 0;
        for (; i < LoginT.permisosxperfil.size(); i++) {
            if (10 == (Integer) LoginT.idspermisosxperfil.get(i)) {
                int confirmar = JOptionPane.showInternalConfirmDialog(this.getRootPane(), "¿Está seguro que desea eliminar el registro?", "Aviso!", JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE);
                if (JOptionPane.OK_OPTION == confirmar) {
                    UsuarioService usuarioservice = new UsuarioService();
                    Integer idusuario = this.listaUsuarios.get(this.tablaUsuarios.getSelectedRow()).getIdusuario();
                    usuarioservice.eliminaUsuario(idusuario);
                    this.RefreshTable();
                    this.inhabilitaBotones();
                }
                break;
            }
            
           
            }
         if (i >= LoginT.permisosxperfil.size()) {
                JOptionPane.showMessageDialog(this, "No puedes proceder, al parecer careces de permisos.",
                        "No posee permisos",
                        JOptionPane.WARNING_MESSAGE);
        }

    }//GEN-LAST:event_btnEliminarActionPerformed

    private void txtNombreKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtNombreKeyPressed
    }//GEN-LAST:event_txtNombreKeyPressed

    private void txtNombreKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtNombreKeyTyped
        // TODO add your handling code here:
    }//GEN-LAST:event_txtNombreKeyTyped

    private void tablaUsuariosMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tablaUsuariosMouseClicked
        if (evt.getClickCount() == 1) {
            this.habilitaBotones();
        }
    }//GEN-LAST:event_tablaUsuariosMouseClicked

    private void botonLimpiarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_botonLimpiarActionPerformed
     this.txtAPaterno.setText("");
     this.txtMaterno.setText("");
     this.txtNombre.setText("");
     this.txtUsuario.setText("");
   //  this.listaEmpleados=
             this.listaUsuarios=new ArrayList<Usuario>();
     
       this.RefreshTable();
    }//GEN-LAST:event_botonLimpiarActionPerformed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton botonBuscar;
    private javax.swing.JButton botonLimpiar;
    private javax.swing.JButton botonNuevo;
    private javax.swing.JButton botonSalir;
    private javax.swing.JButton btnEditar;
    private javax.swing.JButton btnEliminar;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JLabel lblAMaterno;
    private javax.swing.JLabel lblAPaterno;
    private javax.swing.JLabel lblNombre;
    private javax.swing.JLabel lblUsuario;
    private javax.swing.JTable tablaUsuarios;
    private javax.swing.JTextField txtAPaterno;
    private javax.swing.JTextField txtMaterno;
    private javax.swing.JTextField txtNombre;
    private javax.swing.JTextField txtUsuario;
    // End of variables declaration//GEN-END:variables
}
